package com.ktgj.customer.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.constant.AssistProductConstants;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.customer.domain.dto.ProductSelectDTO;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.mapper.CouponMapper;
import com.ktgj.customer.mapper.InsuranceTypeMapper;
import com.ktgj.customer.mapper.MallProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.mapper.AssistProductMapper;
import com.ktgj.customer.domain.AssistProduct;
import com.ktgj.customer.service.IAssistProductService;

/**
 * 辅营产品Service业务层处理
 *
 * @author ruoyi
 * @date 2021-12-20
 */
@Service
public class AssistProductServiceImpl implements IAssistProductService {
    @Autowired
    private AssistProductMapper assistProductMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private InsuranceTypeMapper insuranceTypeMapper;
    @Autowired
    private MallProductMapper mallProductMapper;

    /**
     * 查询辅营产品
     *
     * @param id 辅营产品ID
     * @return 辅营产品
     */
    @Override
    public AssistProduct selectAssistProductById(Long id) {
        return assistProductMapper.selectAssistProductById(id);
    }

    /**
     * 查询辅营产品列表
     *
     * @param assistProduct 辅营产品
     * @return 辅营产品
     */
    @Override
    public List<AssistProduct> selectAssistProductList(AssistProduct assistProduct) {
        assistProduct.setStatus("activation");
        return assistProductMapper.selectAssistProductList(assistProduct);
    }

    /**
     * 新增辅营产品
     *
     * @param assistProduct 辅营产品
     * @return 结果
     */
    @Override
    public int insertAssistProduct(AssistProduct assistProduct) {
        assistProduct.setCreateTime(DateUtils.getNowDate());
        return assistProductMapper.insertAssistProduct(assistProduct);
    }

    /**
     * 修改辅营产品
     *
     * @param assistProduct 辅营产品
     * @return 结果
     */
    @Override
    public int updateAssistProduct(AssistProduct assistProduct) {
        return assistProductMapper.updateAssistProduct(assistProduct);
    }

    /**
     * 批量删除辅营产品
     *
     * @param ids 需要删除的辅营产品ID
     * @return 结果
     */
    @Override
    public int deleteAssistProductByIds(Long[] ids) {
        return assistProductMapper.deleteAssistProductByIds(ids);
    }

    /**
     * 删除辅营产品信息
     *
     * @param id 辅营产品ID
     * @return 结果
     */
    @Override
    public int deleteAssistProductById(Long id) {
        return assistProductMapper.deleteAssistProductById(id);
    }

    @Override
    public List<AssistProductVo> queryAssistProductList(String status, String businessType) {
        List<AssistProductVo> assistProductVos = assistProductMapper.queryAssistProductList(status, businessType);
        return assistProductVos;
    }

    @Override
    public AssistProductVo assistProduct(String status, String businessType, Long id) {
        AssistProductVo assistProductVo = assistProductMapper.assistProduct(status, businessType, id);
        return assistProductVo;
    }

    /**
     * 根据id查询保险产品
     */
    @Override
    public AssistProduct selectProduct(Long id) throws Exception {
        if (id != null && id != 0) {
            AssistProduct assistProduct = assistProductMapper.selectProduct(id);
            if (assistProduct != null && !assistProduct.equals("") &&
                    assistProduct.getStatus().equals("activation") &&
                    assistProduct.getProductType().equals("insurance")) {
            } else {
                return null;
            }
            return assistProduct;
        } else {
            throw new Exception("参数格式不正确");
        }
    }

    @Override
    public AssistProduct queryAssistProduct(Long id) {
        return assistProductMapper.queryAssistProduct(id);
    }

    @Override
    public int insert(AssistProduct assistProduct) {
        assistProduct.setCreateTime(new Date());
        assistProduct.setOperateTime(new Date());
        assistProduct.setDeleted(0l);

        paramAssistProduct(assistProduct);

        return assistProductMapper.insertProduct(assistProduct);
    }

    @Override
    public int update(AssistProduct assistProduct) {
        assistProduct.setOperateTime(new Date());

        paramAssistProduct(assistProduct);

        return assistProductMapper.update(assistProduct);
    }

    @Override
    public List<AssistProduct> select(AssistProduct assistProduct) {
        assistProduct.setDeleted(0l);
        List<AssistProduct> list = assistProductMapper.select(assistProduct);
        for (AssistProduct item : list)
            returnAssistProduct(item);
        return list;
    }

    @Override
    public List<ProductSelectDTO> queryProductSelect(String productType) {
        List<ProductSelectDTO> productSelectDTO = new ArrayList<>();
        if (productType.equals(AssistProductConstants.coupon.getValue())) {
            productSelectDTO = couponMapper.queryCouponSelect();
        } else if (productType.equals(AssistProductConstants.insurance.getValue())) {
            productSelectDTO = insuranceTypeMapper.queryInsuranceTypeSelete();
        } else if (productType.equals(AssistProductConstants.mallProduct.getValue())) {
            productSelectDTO = mallProductMapper.queryMallProductSelect();
        }
        return productSelectDTO;
    }

    @Override
    public int delete(AssistProduct assistProduct) {
        assistProduct.setOperateTime(new Date());

        return assistProductMapper.update(assistProduct);
    }

    public void paramAssistProduct(AssistProduct assistProduct) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < assistProduct.getAirlineList().size(); i++) {
            if (i != 0)
                stringBuffer.append(",");
            stringBuffer.append(assistProduct.getAirlineList().get(i));
        }
        assistProduct.setAirlines(stringBuffer.toString());

        stringBuffer = new StringBuffer();
        for (int i = 0; i < assistProduct.getShowLocationList().size(); i++) {
            if (i != 0)
                stringBuffer.append(",");
            stringBuffer.append(assistProduct.getShowLocationList().get(i));
        }
        assistProduct.setShowLocation(stringBuffer.toString());

        stringBuffer = new StringBuffer();
        for (int i = 0; i < assistProduct.getTripTypeList().size(); i++) {
            if (i != 0)
                stringBuffer.append(",");
            stringBuffer.append(assistProduct.getTripTypeList().get(i));
        }
        assistProduct.setTripType(stringBuffer.toString());

        stringBuffer = new StringBuffer();
        for (int i = 0; i < assistProduct.getShowChannelList().size(); i++) {
            if (i != 0)
                stringBuffer.append(",");
            stringBuffer.append(assistProduct.getShowChannelList().get(i));
        }
        assistProduct.setShowChannel(stringBuffer.toString());

        stringBuffer = new StringBuffer();
        for (int i = 0; i < assistProduct.getBindticketTypeList().size(); i++) {
            if (i != 0)
                stringBuffer.append(",");
            stringBuffer.append(assistProduct.getBindticketTypeList().get(i));
        }
        assistProduct.setBindticketType(stringBuffer.toString());

        Map<String, Object> voluntaryMap = new HashMap<>();
        Map<String, Object> noVoluntaryMap = new HashMap<>();
        for (AssistRefundRule item : assistProduct.getAssistRefundRuleList()) {
            if (item.getRefundType() == RuleRefundType.Voluntary) {
                if (item.getFlyType() == RuleFlyType.flyBefore)
                    voluntaryMap.put("flyBefore", item);
                else
                    voluntaryMap.put("flyAfter", item);
            } else {
                if (item.getFlyType() == RuleFlyType.flyBefore)
                    noVoluntaryMap.put("flyBefore", item);
                else
                    noVoluntaryMap.put("flyAfter", item);
            }
        }
        Map<String, Object> ruleRefundTypeMap = new HashMap<>();
        ruleRefundTypeMap.put("voluntary", voluntaryMap);
        ruleRefundTypeMap.put("noVoluntary", noVoluntaryMap);
        assistProduct.setBackRules(JSON.toJSONString(ruleRefundTypeMap));
    }

    public void returnAssistProduct(AssistProduct assistProduct) {
        List<String> list = null;
        String[] strArr = null;

        if (assistProduct.getAirlines() != null) {
            strArr = assistProduct.getAirlines().split(",");
            list = Arrays.asList(strArr);
            assistProduct.setAirlineList(list);
        }

        list = null;
        strArr = null;
        if (assistProduct.getShowLocation() != null) {
            strArr = assistProduct.getShowLocation().split(",");
            list = Arrays.asList(strArr);
            assistProduct.setShowLocationList(list);
        }


        list = null;
        strArr = null;
        if (assistProduct.getTripType() != null) {
            strArr = assistProduct.getTripType().split(",");
            list = Arrays.asList(strArr);
            assistProduct.setTripTypeList(list);
        }

        list = null;
        strArr = null;
        if (assistProduct.getShowChannel() != null) {
            strArr = assistProduct.getShowChannel().split(",");
            list = Arrays.asList(strArr);
            assistProduct.setShowChannelList(list);
        }

        list = null;
        strArr = null;
        if (assistProduct.getBindticketType() != null) {
            strArr = assistProduct.getBindticketType().split(",");
            list = Arrays.asList(strArr);
            assistProduct.setBindticketTypeList(list);
        }

        JSONObject jsonObject = (JSONObject) JSON.parse(assistProduct.getBackRules());
        assistProduct.setBackRule(jsonObject);
    }


    /*public static void main(String[] args) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            AssistProduct assistProduct = new AssistProduct();
            assistProduct.setId(9l);

            assistProduct.setName("奥迪A8L接机2");//产品名称
            assistProduct.setChannelId(2l);//产品渠道id
            assistProduct.setDescribe("准时守候，奥迪让你一路畅享无忧！");//简介
            assistProduct.setBuyMinnum(0l);//购买份数最小数，不限制为-1
            assistProduct.setBuyMaxnum(1l);//购买份数最大数，不限制为-1
            assistProduct.setDatelimit(AssistProductConstants.notAvailable.getValue());//时间限制
            assistProduct.setBookingDateStart(simpleDateFormat.parse("2018-07-17"));//预订开始时间
            assistProduct.setBookingDateEnd(simpleDateFormat.parse("2018-07-30"));//预订结束时间
            assistProduct.setDepartureDateStart(simpleDateFormat.parse("2018-07-17"));//起飞开始时间
            assistProduct.setDepartureDateEnd(simpleDateFormat.parse("2018-07-30"));//起飞结束时间
            assistProduct.setAgeMinnum(4831l);//年龄限制最小数（天）
            assistProduct.setAgeMaxnum(36500l);//年龄限制最大数（天）
            assistProduct.setPriceType(AssistProductConstants.amountOfMoney.getValue());//销售，结算价类型
            assistProduct.setUnderlinePrice(new BigDecimal(39));//销售价格
            assistProduct.setSalePrice(new BigDecimal(0));//结算价格
            assistProduct.setMemberPrice(new BigDecimal(38));//会员价
            assistProduct.setCostPrice(new BigDecimal(200));//价值（展示面价）
            assistProduct.setBackChangeFee(new BigDecimal(0));//退改费用
            assistProduct.setDefaultCheck(1l);//默认选中 0否 1是
            assistProduct.setStatus(AssistProductConstants.notEnabled.getValue());//是否启用
            assistProduct.setIsBack(1l);//是否可退 0否 1是
            assistProduct.setIscheck(AssistProductConstants.optional.getValue());//销售模式
            assistProduct.setFlylimittime(24l);//展示受限
            assistProduct.setSourceType(AssistProductConstants.selfSupport.getValue());//来源类型
            assistProduct.setDetailsfull("");//详细说明富文本
            assistProduct.setEnableAirline("ALL|TAO,ALL|TNA,ALL|DLC,ALL|SHE,ALL|CGQ");//适用航线
            assistProduct.setDisabledAirline("");//不适用航线
            assistProduct.setAloneShow(0l);//产品是否单列 0否 1是
            assistProduct.setProductType(AssistProductConstants.mallProduct.getValue());//产品类型
            assistProduct.setProductTypeid(1l);//产品id
            assistProduct.setValidityType(AssistProductConstants.takeoff.getValue());//有效时间参照物
            assistProduct.setValidity(2l);//有效期(单位/天)
            assistProduct.setArriveDateStart(simpleDateFormat.parse("2018-07-30"));//到达开始时间
            assistProduct.setArriveDateEnd(simpleDateFormat.parse("2018-07-30"));//到达结束时间
            assistProduct.setIslimitDeparture(1l);//是否限制起飞时间 0限制 1不限制
            assistProduct.setIslimitArrive(1l);//是否限制到达时间 0限制 1不限制
            assistProduct.setRemaid("");//强制提醒
            assistProduct.setShowPosition(AssistProductConstants.vertical.getValue());//预定页面展示位置
            assistProduct.setExplain("服务城市：青岛、济南、大连、沈阳、长春\n" +
                    "车型：奥迪A8L\n" +
                    "接送机范围：市区内不限公里数，期间中途不等待不停留\n" +
                    "车辆备品：矿泉水（怡宝）、纸巾、湿巾、晕车贴、方便袋、雨伞、调查问卷（上车后H5操作）\n" +
                    "乘坐人数：3成人+1儿童（单次）\n" +
                    "最大行李数：28寸旅行箱2只\n" +
                    "航班到达时间段范围：9：00-16：00\n" +
                    "预约流程：下单后会有工作人员与您联系，确认约车时间以及地点\n" +
                    "退订规则：非不可抗拒的原因外，原则上不得自愿退款。\n" +
                    "使用有效期：航班日当天2日内使用有效\n" +
                    "订单份数限制：每单仅限购买一份，多买无效\n" +
                    "备注:本次活动为体验活动，数量有限，先到先得，如遇车辆约满或时间不满意可全额退款");//详细说明
            assistProduct.setBusinessType(BusinessTypeConstants.specialCar.getValue());//业务类型
            List<String> airlineList = new ArrayList<>();
            airlineList.add("9C");
            airlineList.add("DR");
            airlineList.add("9C");
            assistProduct.setAirlineList(airlineList);//适用航空公司
            List<String> bindticketTypeList = new ArrayList<>();
            bindticketTypeList.add("Spring");
            bindticketTypeList.add("cashBack");
            bindticketTypeList.add("official");
            assistProduct.setBindticketTypeList(bindticketTypeList);//绑定机票类型
            List<String> tripTypeList = new ArrayList<>();
            tripTypeList.add("OW");
            tripTypeList.add("RT");
            tripTypeList.add("MP");
            assistProduct.setTripTypeList(tripTypeList);//航班类型
            List<String> showLocationList = new ArrayList<>();
            showLocationList.add("shippingSpace");
            showLocationList.add("reserve");
            showLocationList.add("order");
            assistProduct.setShowLocationList(showLocationList);//展示位置
            List<String> showChannelList = new ArrayList<>();
            showChannelList.add("online");
            showChannelList.add("phone");
            showChannelList.add("Import");
            assistProduct.setShowChannelList(showChannelList);//展示渠道
            List<AssistRefundRule> assistRefundRuleList = new ArrayList<>();
            AssistRefundRule a1 = new AssistRefundRule();
            AssistRefundRule a2 = new AssistRefundRule();
            AssistRefundRule a3 = new AssistRefundRule();
            AssistRefundRule a4 = new AssistRefundRule();
            a1.setRefundType(RuleRefundType.Voluntary);
            a1.setFlyType(RuleFlyType.flyBefore);
            a1.setTimeType(RuleTimeType.before);
            a1.setTimeValue("2");
            a1.setFeeRate(100);
            a2.setRefundType(RuleRefundType.Voluntary);
            a2.setFlyType(RuleFlyType.flyAfter);
            a2.setTimeType(RuleTimeType.before);
            a2.setTimeValue("2");
            a2.setFeeRate(0);
            a3.setRefundType(RuleRefundType.NoVoluntary);
            a3.setFlyType(RuleFlyType.flyBefore);
            a3.setTimeType(RuleTimeType.before);
            a3.setTimeValue("2");
            a3.setFeeRate(100);
            a4.setRefundType(RuleRefundType.NoVoluntary);//自愿：Voluntary、非自愿：NoVoluntary
            a4.setFlyType(RuleFlyType.flyAfter);//起飞前：flyBefore、起飞后：flyAfter
            a4.setTimeType(RuleTimeType.before);//之前：before、之后：after、以内：in
            a4.setTimeValue("2");//几小时
            a4.setFeeRate(0);//手续费百分点
            assistRefundRuleList.add(a1);
            assistRefundRuleList.add(a2);
            assistRefundRuleList.add(a3);
            assistRefundRuleList.add(a4);
            assistProduct.setAssistRefundRuleList(assistRefundRuleList);//手续费规则数据集合
            System.out.println(JSON.toJSONString(assistProduct));
        } catch (ParseException e) {
            System.out.println("时间转化错误");
        }
    }*/
}
/*
        assistProduct.setId();
        assistProduct.setAirlines();
        assistProduct.setShowLocation();
        assistProduct.setTripType();
        assistProduct.setShowChannel();
        assistProduct.setBindticketType();
        assistProduct.setBackRules();

            assistProduct.setOperateTime();
            assistProduct.setOpemployeeid();


            assistProduct.setTicketType();
            assistProduct.setSort();
            assistProduct.setConvertId();
            assistProduct.setLogId();
            assistProduct.setFlightno();
            assistProduct.setProductimg();
            assistProduct.setProducttypeimg();



 */